package com.hanbang.taitaigou.ui.activity.aboutme.address;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;


import com.hanbang.taitaigou.R;
import com.hanbang.taitaigou.ui.activity.base.BaseActivity;
import com.hanbang.taitaigou.utils.http.HttpCallBack;
import com.hanbang.taitaigou.utils.http.HttpRequestParams;
import com.hanbang.taitaigou.utils.ui.UiUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;

public class CitySelectActivity extends BaseActivity {

    /**
     * 当前状态，用来控制listView显示  1：省份，2：城市  3：区域
     */
    private int status = 1;

    /**
     * 省份数据
     */
    private ArrayList<String> sfDatas = new ArrayList<>();

    /**
     * 城市数据
     */
    private ArrayList<String> cityDatas = new ArrayList<>();

    /**
     * 区域数据
     */
    private ArrayList<String> quyuDatas = new ArrayList<>();

    /**
     * 适配器
     *
     * @param savedInstanceState
     */
    private MyAdapter adapter = null;

    private String[] action = {"GetProvince", "GetCity", "GetArea"};
    private String[] jsonResultItem = {"provinceName", "cityName", "areaName"};

    /**
     * 当前选择的位置
     */
    private int sfPosition = -1, cityPosition = -1, quyuPosition = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.city_select);
        initView();
        setOnClickListener();
        /**
         * 获取服务器先获取省份数据
         */
        getSerViceDatas(1);
    }

    /**
     * 获取服务器数据
     * 1：省份，2：城市  3：区域
     * p 0-2个，第一个：省份的名字，第二个：城市的名字
     */
    private void getSerViceDatas(final int type, final String... p) {
        HttpRequestParams params = new HttpRequestParams(action[type - 1]);
        if (type == 2) {
            params.addBodyParameter("province", p[0]);
        } else if (type == 3) {
            params.addBodyParameter("province", p[0]);
            params.addBodyParameter("city", p[1]);
        }
        httpManager.post(params, new HttpCallBack<String>(this, getString(R.string.loadding)) {

            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject json = new JSONObject(result);
                    JSONArray res = json.getJSONArray("result");
                    if (type == 1) {
                        sfDatas.clear();
                    } else if (type == 2) {
                        cityDatas.clear();
                    } else if (type == 3) {
                        quyuDatas.clear();
                    }
                    for (int i = 0; i < res.length(); i++) {
                        String str = res.getJSONObject(i).getString(jsonResultItem[type - 1]);
                        if (type == 1) {
                            sfDatas.add(str);
                        } else if (type == 2) {
                            cityDatas.add(str);
                        } else if (type == 3) {
                            quyuDatas.add(str);
                        }
                    }
                    /**
                     * 更新ui
                     */
                    upDataUi(type, p);


                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }


        });

    }

    /**
     * 更新ui
     */
    private void upDataUi(int type, String... p) {
        status = type;
        //标题的显示与否
        if (status == 1) {
            //都不显示
            if (shengfen.getVisibility() == View.VISIBLE) {
                //执行关闭动画
                viewAnmin(shengfen, 2);
            }
            if (city.getVisibility() == View.VISIBLE) {
                //执行关闭动画
                viewAnmin(city, 2);
            }
        } else if (status == 2) {
            shengfen.setText(p[0]);
            //显示省份
            if (shengfen.getVisibility() == View.GONE) {
                shengfen.setVisibility(View.VISIBLE);
                //执行开启动画
                viewAnmin(shengfen, 1);
            }
            if (city.getVisibility() == View.VISIBLE) {
                //执行关闭动画
                viewAnmin(city, 2);
            }

        } else if (status == 3) {
            shengfen.setText(p[0]);
            city.setText(p[1]);
            //显示 省份与城市
            if (shengfen.getVisibility() == View.GONE) {
                shengfen.setVisibility(View.VISIBLE);
                //执行开启动画
                viewAnmin(shengfen, 1);
            }
            if (city.getVisibility() == View.GONE) {
                //执行开启动画
                city.setVisibility(View.VISIBLE);
                viewAnmin(city, 1);
            }

        }
        adapter.notifyDataSetChanged();
    }

    /**
     * 执行动画
     */
    private void viewAnmin(final TextView v, int type) {
        if (type == 1) {
            //打开动画
            PropertyValuesHolder holder = PropertyValuesHolder.ofFloat("translationY", -v.getMeasuredHeight(), 0);
            ObjectAnimator.ofPropertyValuesHolder(v, holder).setDuration(300).start();
        } else if (type == 2) {
            //关闭动画
            PropertyValuesHolder holder = PropertyValuesHolder.ofFloat("rotationX", 0, -70);
            ObjectAnimator objectAnimator = ObjectAnimator.ofPropertyValuesHolder(v, holder);
            objectAnimator.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationCancel(Animator animation) {
                    super.onAnimationCancel(animation);
                    v.setVisibility(View.GONE);
                    v.setRotationX(0);
                    v.setText("");
                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    v.setVisibility(View.GONE);
                    v.setRotationX(0);
                    v.setText("");
                }
            });
            objectAnimator.setDuration(300).start();
        }
    }

    /*
     * 设置点击事件
     */
    private void setOnClickListener() {

    }

    @SuppressWarnings("unused")
    private OnClickListener onClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {

                default:
                    break;
            }
        }
    };

//    @Event(value = R.id.top_bar_left_group, type = OnClickListener.class)
//    private void backOnClick(View v) {
//        onBackPressed();
//    }

    /**
     * 省份的点击事件
     */
    @Event(value = R.id.shengfen, type = OnClickListener.class)
    private void shengfenOnClick(View v) {
        if (status == 3 || status == 2) {
            upDataUi(1);
        }
    }

    /**
     * 城市的点击事件
     */
    @Event(value = R.id.city, type = OnClickListener.class)
    private void cityfenOnClick(View v) {
        if (status == 3) {
            upDataUi(2, sfDatas.get(sfPosition));
        }
    }

    @Override
    public void onBackPressed() {
        if (status == 1) {
            //退出
            finish();
        } else if (status == 2) {
            //退到省份
            status = 1;
            cityPosition = -1;
            cityDatas.clear();
            adapter.notifyDataSetChanged();
            upDataUi(status);
        } else if (status == 3) {
            //退到城市
            status = 2;
            quyuPosition = -1;
            quyuDatas.clear();
            adapter.notifyDataSetChanged();
            upDataUi(status, sfDatas.get(sfPosition));
        }
    }

    /**
     * 回退事件
     */
    /*
     * 初始化view
     */
    private void initView() {
        // 设置顶部的标题
        setTop(null, 0, getString(R.string.top_city_select), null, 0);
        setBackArrows(findViewById(R.id.top_bar_left_iv));
        adapter = new MyAdapter();
        listView.setAdapter(adapter);
        city.setPivotX(0);
        shengfen.setPivotX(0);
        int w = View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED);
        city.measure(w, h);
        shengfen.measure(w, h);
    }


    /**
     * listVIew的点击事件
     */
    @Event(value = R.id.listview, type = AdapterView.OnItemClickListener.class)
    private void listOnItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (status == 1) {
            //省份被点击,，根据省份获取城市信息
            getSerViceDatas(2, sfDatas.get(position));
            sfPosition = position;
        } else if (status == 2) {
            //城市被点击,  根据省份与城市获取区域信息
            getSerViceDatas(3, sfDatas.get(sfPosition), cityDatas.get(position));
            cityPosition = position;

        } else if (status == 3) {
            //区域被点击，设置返回值
            quyuPosition = position;
            Intent intent = new Intent();
            intent.putExtra("sf", sfDatas.get(sfPosition));
            intent.putExtra("city", cityDatas.get(cityPosition));
            intent.putExtra("quyu", quyuDatas.get(quyuPosition));
            setResult(AboutMeAddAddressManagementActivity.CITY_SELECT_FLAG, intent);
            finish();
        }
    }

    /**
     * listView 适配器
     */
    private class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            if (status == 1) {
                return sfDatas.size();
            } else if (status == 2) {
                return cityDatas.size();
            } else if (status == 3) {
                return quyuDatas.size();
            }
            return 0;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.city_select_listitem, null);
                holder = new ViewHolder();
                holder.title = (TextView) convertView.findViewById(R.id.title);
                UiUtils.applyFont(convertView);
                convertView.setTag(holder);

            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            if (status == 1) {
                holder.title.setText(sfDatas.get(position));
            } else if (status == 2) {
                holder.title.setText(cityDatas.get(position));
            } else if (status == 3) {
                holder.title.setText(quyuDatas.get(position));
            }
            return convertView;
        }

        private class ViewHolder {
            TextView title;
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @ViewInject(R.id.shengfen)
    private TextView shengfen;
    @ViewInject(R.id.city)
    private TextView city;
    @ViewInject(R.id.listview)
    private ListView listView;
}
